package com.sp.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 演示通过反射机制创建实例
 */
public class ReflectCreateInstance {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //1. 先获取到User类的Class对象
        Class<?> userClass = Class.forName("com.sp.reflection.User");

        //2. 通过public的无参构造器创建实例
        Object o = userClass.newInstance();
        System.out.println(o);

        //3. 通过public的有参构造器创建实例
        /*
        这里的 constructor 对象就是 User 类里面的一个有参构造器
            public User(String name) {
                this.name = name;
            }
         */
        Constructor<?> constructor = userClass.getConstructor(String.class);
        Object sp1 = constructor.newInstance("sp1");
        System.out.println("sp1 = " + sp1);

        //4. 通过非public的无参构造器创建实例
        //4.1 得到private 的构造器对象
        Constructor<?> constructor1 = userClass.getDeclaredConstructor(int.class, String.class);
        //4.2 创建实例
        //暴破[暴力破解], 使用反射可以访问 private 修饰的构造器/方法/属性
        constructor1.setAccessible(true);
        Object o1 = constructor1.newInstance(100, "张三丰");
        System.out.println(o1);
    }
}

class User {
    private int age = 10;
    private String name = "sp";

    public User() {//无参构造器
    }

    public User(String name) {
        this.name = name;
    }
    private User(int age, String name) {
        this.age = age;
        this.name = name;
    }
    public String toString() {
        return "User [age=" + age + ", name=" + name + "]";
    }
}